package cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.controller.admin.order;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goods.dal.dataobject.goods.GoodsDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goods.dal.mysql.goods.GoodsMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.supplier.dal.dataobject.supplier.SupplierDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.supplier.dal.mysql.supplier.SupplierMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.controller.admin.order.vo.OrderGood;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.controller.admin.order.vo.OrderLogistic;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.controller.admin.order.vo.OrderPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.kuaidi.KuaiDiProvider;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.service.order.OrderService;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.controller.admin.order.vo.OrderExcelVO;
import cn.iocoder.yudao.module.system.controller.admin.mini.userInfo.user.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.userInfo.user.dal.mysql.user.QdUserMapper;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 小程序-订单")
@RestController
@RequestMapping("/qd/order")
@Validated
public class OrderController {

    @Resource
    private OrderService orderService;
    @Resource
    OrderMapper orderMapper;
    @Resource
    QdUserMapper userMapper;
    @Resource
    SupplierMapper supplierMapper;
    @Resource
    GoodsMapper goodsMapper;

    @GetMapping("/findLogistics")
    @Operation(summary = "查看物流")
    public CommonResult findLogistics(Integer id) throws IllegalAccessException {
        OrderDO orderDO = orderMapper.selectById(id);
        if (orderDO==null)
            throw new ServiceException(500,"无此数据,请刷新");
        if (orderDO.getLogistic()==null)
            throw new ServiceException(500,"未添加物流");

        return success(KuaiDiProvider.getKuaiDiInfo(orderDO.getLogistic().getCode(),orderDO.getLogistic().getNum()));
    }

    @GetMapping("pickingUpGoods")
    @Operation(summary = "取货")
    public CommonResult pickingUpGoods(Integer id,String code){
        OrderDO orderDO = orderMapper.selectById(id);
        if (orderDO.getOrderStatus()!=3)
            throw new ServiceException(500,"订单无处于待取货");
        if (!orderDO.getPickUpCode().equals(code))
            throw new ServiceException(500,"取货码错误");
        orderDO.setOrderStatus(4);
        orderDO.setQhTime(LocalDateTime.now());

        orderMapper.updateById(orderDO);
        return success("");
    }


    @PostMapping("/addLogistics")
    @Operation(summary = "发货")
    public CommonResult addLogistics(@RequestBody OrderLogisticVo vo) {
        OrderDO orderDO = orderMapper.selectById(vo.getId());
        if (orderDO==null)
            throw new ServiceException(500,"无此数据,请刷新");
        if (orderDO.getPickUpCode()!=null)
            throw new ServiceException(500,"物流已发送");

        // 创建一个Random对象
        Random random = new Random();
        // 使用nextInt()方法生成0到9之间的随机整数
        int number1 = random.nextInt(10);
        int number2 = random.nextInt(10);
        int number3 = random.nextInt(10);
        int number4 = random.nextInt(10);

        String code = orderDO.getOrderCode();
        // 将每个随机数转换为字符串并连接起来形成四位随机数
        String fourDigitRandomNum = code.substring(code.length()-2,code.length()) + number1 + number2 + number3 + number4;
        orderDO.setPickUpCode(fourDigitRandomNum);
        orderDO.setOrderStatus(3);

        orderMapper.updateById(orderDO);
        return success("");
    }



//    @PostMapping("/addLogistics")
//    @Operation(summary = "添加物流")
//    public CommonResult addLogistics(@RequestBody OrderLogisticVo vo) {
//        OrderDO orderDO = orderMapper.selectById(vo.getId());
//        if (orderDO==null)
//            throw new ServiceException(500,"无此数据,请刷新");
//        if (orderDO.getLogistic()!=null)
//            throw new ServiceException(500,"物流已存在,请刷新");
//        orderDO.setLogistic(vo.getDto());
//        orderDO.setOrderStatus(3);
//        orderDO.setLogisticTime(LocalDateTime.now());
//        orderMapper.updateById(orderDO);
//        return success("");
//    }

        @PostMapping("/create")
    @Operation(summary = "创建小程序-订单")
    @PreAuthorize("@ss.hasPermission('qd:order:create')")
    public CommonResult<Integer> createOrder(@Valid @RequestBody OrderDO createReqVO) {
        return success(orderService.createOrder(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新小程序-订单")
    @PreAuthorize("@ss.hasPermission('qd:order:update')")
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody OrderDO updateReqVO) {
        orderService.updateOrder(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除小程序-订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('qd:order:delete')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Integer id) {
        orderService.deleteOrder(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得小程序-订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('qd:order:query')")
    public CommonResult<OrderDO> getOrder(@RequestParam("id") Integer id) {
        return success(orderService.getOrder(id));
    }

//    @GetMapping("/list")
//    @Operation(summary = "获得小程序-订单列表")
//    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
//    @PreAuthorize("@ss.hasPermission('qd:order:query')")
//    public CommonResult<List<OrderRespVO>> getOrderList(@RequestParam("ids") Collection<Integer> ids) {
//        List<OrderDO> list = orderService.getOrderList(ids);
//        return success(OrderConvert.INSTANCE.convertList(list));
//    }

    @GetMapping("/page")
    @Operation(summary = "获得小程序-订单分页")
    @PreAuthorize("@ss.hasPermission('qd:order:query')")
    public CommonResult<PageResult<OrderDO>> getOrderPage(@Valid OrderPageReqVO pageVO) {
        PageResult<OrderDO> orderPage = orderService.getOrderPage(pageVO);
        List<OrderDO> list = orderPage.getList();
        for (OrderDO orderDO : list) {
            String phone="";
            UserDO userDO = userMapper.selectById(orderDO.getCreator());
            if (userDO!=null){
                orderDO.setPhone(phone);
            }
        }
        orderPage.setList(list);
        return success(orderPage);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出")
    @OperateLog(type = EXPORT)
    public void exportOrderExcel(@Valid OrderPageReqVO pageVO,
              HttpServletResponse response) throws IOException {

        //userId phone
        Map<Integer,String> map=new HashMap<>();
        for (UserDO userDO : userMapper.selectList()) {
            map.put(userDO.getId(),userDO.getPhone());
        }
        List<OrderDO> orderDOS = orderMapper.selectList(pageVO);
        for (OrderDO orderDO : orderDOS) {
            String phone="";
            String value = map.get(Integer.parseInt(orderDO.getCreator()));
            if (value!=null)
                phone=value;
            orderDO.setPhone(phone);
        }
        //商品id  供应商id
        Map<Integer,Integer> goodMap=new HashMap<>();
        for (GoodsDO vo : goodsMapper.selectList()) {
            if (vo.getSupplierId()!=null)
                goodMap.put(vo.getId(),vo.getSupplierId());
        }
        //供应商id 供应商名称
        Map<Integer,String> supMap=new HashMap<>();
        for (SupplierDO vo : supplierMapper.selectList()) {
            supMap.put(vo.getId(),vo.getName());
        }

        List<OrderExcelVO> list=new ArrayList<>();
        for (OrderDO orderDO : orderDOS) {
            for (OrderGood good : JSON.parseArray(orderDO.getGoods().toString(),OrderGood.class)) {
                String supName="";
                Integer supId = goodMap.get(good.getGoodsId());
                if (supId!=null){
                    supName=supMap.get(supId);
                }
                list.add(new OrderExcelVO(orderDO,good.getGoodsName(),supName,good.getGoodsId()));

            }
        }

        ExcelUtils.write(response, "订单表.xls", "数据", OrderExcelVO.class, list);
    }

}
@Data
class OrderLogisticVo{
    Integer id;
    OrderLogistic dto;
}
